package com.mapull.simple;

import java.util.Arrays;

/**
 * 快速排序-单边循环
 *
 * @author mapull
 * @date 2022-06-05
 */
public class QuickSingle {

    public static void main(String[] args) {
        int[] nums = {5, 9, 7, 4, 1, 8, 3, 2, 6};
        System.out.println("排序前 " + Arrays.toString(nums));
        quickSort(nums, 0, nums.length - 1);
        System.out.println("排序后 " + Arrays.toString(nums));
    }

    private static void quickSort(int[] nums, int left, int right){
        if(left >= right){
            return;
        }
        int cur = partition(nums, left, right);
        quickSort(nums, left, cur -1);
        quickSort(nums, cur + 1, right);
    }

    private static int partition(int[] nums, int left, int right) {
        int i = left;
        int pv = nums[right];
        for (int j = left; j < right; j++) {
            if (nums[j] < pv) {
                System.out.println("交换 " + nums[i] + " 与 " + nums[j] + "; ");
                swap(nums, i, j);
                i++;
            }
        }
        swap(nums, right, i);
        System.out.println("i=" + i + "，数组为 " + Arrays.toString(nums));
        return i;
    }

    private static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
